import { Widget } from '@/models'
import { RawField, TextDefault, WidgetData } from '@/types'
import { normalizeModel } from '@/utils'

/** 初始控件文本数据 */
export function initTextData(widget: Widget, data: WidgetData) {
  widget.text = { ...TextDefault, ...widget.option.text, ...normalizeModel(data.text || {}) }
}

/** 根据原始控件数据创建文本控件扩展 */
export function rawTextCreator(widgetData: WidgetData, data: RawField) {
  const { fontSize, fontType: fontFamily, align: textAlign, placeholder } = data

  return Object.assign(widgetData, {
    text: {
      fontSize,
      fontFamily,
      textAlign,
      placeholder
    }
  } as WidgetData)
}

/** 根据文本控件获取原始控件数据扩展 */
export function rawTextGetter(widget: Widget, data: RawField) {
  const { textAlign: align, fontSize, fontFamily: fontType, placeholder } = { ...TextDefault, ...widget.text }

  return Object.assign(data, {
    fontSize,
    fontType,
    align,
    placeholder
  } as RawField)
}

/** 文本框控件使用校验 */
export function usingValidate(widget: Widget) {
  /** 填写控件必填校验 */
  if (widget.required && !widget.hasFillValue) {
    const sourceName = widget.sourceItem?.name

    return sourceName ? `${sourceName}获取失败` : `请输入${widget.displayName}`
  }
}

/** 文本控件 placeholder 占位 */
export function getTextPlaceholder(widget: Widget) {
  return widget.isDone ? '' : widget.sourceItem?.name || widget.text.placeholder || `请输入${widget.displayName}`
}

/** 单行文本可输入字数提示 */
export function getInputTextTips(widget: Widget) {
  const {
    w,
    h,
    text: { fontSize, maxLength }
  } = widget

  let count = Math.max(Math.floor(w / fontSize))

  if (maxLength) {
    count = Math.min(count, maxLength)
  }

  count = Math.max(count, 1)

  return `可输入${count}字`
}

/** 多行文本可输入字数和行数提示 */
export function getTextareaTextTips(widget: Widget) {
  const {
    w,
    h,
    text: { fontSize, maxLength }
  } = widget

  const line = Math.max(Math.floor(h / fontSize), 1)
  let count = Math.floor(w / fontSize) * line

  if (maxLength) {
    count = Math.min(count, maxLength)
  }

  count = Math.max(count, 1)

  return `可输入${line}行共${count}字`
}
